<template>
  <el-dialog :title="pageTitle" :close-on-click-modal="false" :close-on-press-escape="false"
             :visible.sync="visible" lock-scroll append-to-body
             class="wpwork-dialog wpwork-dialog_center transfer-dialog" width="1000px">
    <div class="transfer__body" v-loading="allLoading">
      <div class="transfer-pane">
        <div class="transfer-pane__tools">
          <el-input placeholder="请输入关键词查询" v-model="keyword" @keyup.enter.native="search" clearable
                    class="search-input">
            <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
          </el-input>
        </div>
        <div class="transfer-pane__body left-pane">
          <!-- 用户列表 -->
          <el-table
            ref="userTable"
            :data="filteredUserList"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            v-loading="loading">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              prop="groupName"
              label="群名"
              width="150">
            </el-table-column>
            <el-table-column
              prop="realName"
              label="姓名"
              width="140">
            </el-table-column>
            <el-table-column
              prop="type"
              label="类型"
              width="80">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.type === 'person'" size="small" type="success">个人</el-tag>
                <el-tag v-else size="small" type="primary">群组</el-tag>
              </template>
            </el-table-column>
          </el-table>

          <!-- 统计信息 -->
          <div class="list-stats">
            共 {{ filteredUserList.length }} 个联系人
          </div>
        </div>
      </div>
      <div class="transfer-pane">
        <div class="transfer-pane__tools">
          <span>已选择用户</span>
          <el-button @click="removeAll" type="text" class="removeAllBtn">清空列表</el-button>
        </div>
        <div class="transfer-pane__body shadow right-pane">
          <template v-if="selectedData.length">
            <div v-for="(item,index) in selectedData" :key="index" class="selected-item-user">
              <div class="selected-item-main">
                <el-avatar :size="36" :src="getAvatarUrl(item.headIcon)"
                           class="selected-item-headIcon">
                  <i v-if="!item.headIcon" class="el-icon-user"></i>
                </el-avatar>
                <div class="selected-item-text">
                  <p class="name">{{item.realName}}</p>
                  <p class="organize" :title="item.account">{{item.account}}</p>
                  <p class="type-tag">
                    <el-tag v-if="item.type === 'person'" size="mini" type="success">个人</el-tag>
                    <el-tag v-else size="mini" type="primary">群组</el-tag>
                  </p>
                </div>
                <i class="el-icon-delete" @click="removeData(item.id)"></i>
              </div>
            </div>
          </template>
          <el-empty description="暂无选择用户" :image-size="120" v-else></el-empty>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{$t('common.cancelButton')}}</el-button>
      <el-button type="primary" :loading="btnLoading" @click="confirmSelection">
        {{$t('common.confirmButton')}}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { groupsPersons,PersonsGroupNames } from '@/api/message'

export default {
  data() {
    return {
      visible: false,
      loading: false,
      btnLoading: false,
      allLoading: false,
      pageTitle: '选择用户',
      userList: [], // 原始用户列表数据
      selectedData: [], // 已选用户数据
      keyword: '',
      multipleSelection: [], // 表格选中的行
      define: {
        comUrl: process.env.VUE_APP_CDN || '/api/file/Image/userAvatar/' // 根据你的项目配置调整
      }
    }
  },
  computed: {
    // 过滤后的用户列表（前端搜索）
    filteredUserList() {
      if (!this.keyword) {
        return this.userList;
      }
      const searchLower = this.keyword.toLowerCase();
      return this.userList.filter(user =>
        user.realName.toLowerCase().includes(searchLower) ||
          user.groupName.toLowerCase().includes(searchLower)
      );
    },
    // 个人用户数量
    personCount() {
      return this.filteredUserList.filter(user => user.type === 'person').length;
    },
    // 群组数量
    groupCount() {
      return this.filteredUserList.filter(user => user.type === 'group').length;
    }
  },
  methods: {
    init() {
      this.visible = true
      this.userList = []
      this.selectedData = []
      this.keyword = ''
      this.multipleSelection = []
      console.log('init',this.filteredUserList)
      this.$nextTick(() => {
        this.allLoading = true
        this.initData()
      })
    },

    search() {
      // 前端搜索，无需重新请求接口
    },

    // 初始化用户列表
    async initData() {
      this.loading = true
      try {
        const response = await PersonsGroupNames()
        if (response.code === 200) {
          // 转换数据结构
          this.userList = this.transformUserData(response.data || [])
          console.log('转换后的用户列表:', this.userList)
        } else {
          this.$message.error(response.msg || '获取用户数据失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.$message.error('获取用户数据失败')
      } finally {
        this.loading = false
        this.allLoading = false
      }
    },

    // 转换数据结构
    transformUserData(data) {
      return data.map(item => ({
        id: item.groupId,
        realName: item.groupRealname,
        account: item.groupName,
        headIcon: item.groupIcon,
        type: item.grouptype,// 'person' 或 'group'
        groupName : item.groupParentName
      }))
    },

    // 获取头像URL
    getAvatarUrl(iconPath) {
      if (!iconPath) return '';
      // 如果已经是完整URL，直接返回
      if (iconPath.startsWith('http')) {
        return iconPath;
      }
      // 否则拼接基础URL
      return `${this.define.comUrl}${iconPath}`;
    },

    // 设置表格选中状态
    setTableSelection() {
      this.$refs.userTable.clearSelection()
      this.filteredUserList.forEach(row => {
        if (this.selectedData.some(selected => selected.id === row.id)) {
          this.$refs.userTable.toggleRowSelection(row, true)
        }
      })
    },

    // 表格选择变化
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      // 将选中的用户添加到已选列表（去重）
      selection.forEach(row => {
        if (!this.selectedData.some(selected => selected.id === row.id)) {
          this.selectedData.push({
            id: row.id,
            realName: row.realName,
            account: row.account,
            headIcon: row.headIcon,
            type: row.type
          })
        }
      })
      // 从已选列表中移除未选中的用户
      this.selectedData = this.selectedData.filter(selected =>
        selection.some(row => row.id === selected.id)
      )
    },

    removeAll() {
      this.$confirm('确定清空所有已选择用户吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.selectedData = []
        this.multipleSelection = []
        this.$refs.userTable.clearSelection()
      }).catch(() => {
      })
    },

    removeData(userId) {
      const index = this.selectedData.findIndex(item => item.id === userId)
      if (index !== -1) {
        this.selectedData.splice(index, 1)
        // 同时移除表格中的选中状态
        const row = this.filteredUserList.find(row => row.id === userId)
        if (row) {
          this.$refs.userTable.toggleRowSelection(row, false)
        }
      }
    },

    // 确认选择
    confirmSelection() {
      if (this.selectedData.length === 0) {
        this.$message.warning('请至少选择一个用户')
        return
      }

      // 触发用户选择事件，传递选中的用户数据
      this.$emit('user-selected', this.selectedData)
      this.visible = false
      this.btnLoading = false
    }
  }
}
</script>

<style scoped>
.transfer__body {
  display: flex;
  height: 500px;
}

.transfer-pane {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin: 0 10px;
}

.transfer-pane__tools {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.transfer-pane__body {
  flex: 1;
  overflow: auto;
  padding: 10px;
}

.selected-item-user {
  margin-bottom: 10px;
  padding: 8px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}

.selected-item-main {
  display: flex;
  align-items: center;
}

.selected-item-headIcon {
  margin-right: 10px;
}

.selected-item-text {
  flex: 1;
}

.selected-item-text .name {
  margin: 0;
  font-weight: 500;
}

.selected-item-text .organize {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.selected-item-text .type-tag {
  margin: 2px 0 0 0;
}

.el-icon-delete {
  color: #f56c6c;
  cursor: pointer;
}

.el-icon-delete:hover {
  color: #f78989;
}

.list-stats {
  margin-top: 10px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}
</style>
